package com.hundsun.yr.universal.library.view.gallery;

import com.hundsun.yr.universal.library.R;
import com.nineoldandroids.view.ViewHelper;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;


/**
 * @Title: HSGallery.java 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @date 2015-12-14 上午11:27:11 
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com 
 * @replace author:
 * @replace date:
 * @version V1.0   
 */
public class HSGallery extends RelativeLayout{

	public static float GALLEY_SCALE_RATE = 0.9f;
    private WrapContentHeightViewPager   viewPager;
    private static int OFFSCREEN_PAGE_LIMIT = 2;
    private HSGalleryPagerAdapter<Object> hsGalleryPagerAdapter;

    private int galleryPaddingLeft = getResources().getDimensionPixelSize(R.dimen.gallery_left_margin);
    private int galleryPaddingRight = getResources().getDimensionPixelSize(R.dimen.gallery_right_margin);
    private int galleryPaddingTop = getResources().getDimensionPixelSize(R.dimen.gallery_top_margin);
    private int galleryPaddingBottom = getResources().getDimensionPixelSize(R.dimen.gallery_bottom_margin);
    private int galleryCenterMargin = getResources().getDimensionPixelSize(R.dimen.gallery_center_margin);
    
    private static final boolean API_11;
	static {
		API_11 = Build.VERSION.SDK_INT >= 11;
	}
    private State mState = State.IDLE;
	private int oldPage;

	private View mLeft;
	private View mRight;

	private float mScale;
	
	private HSGalleryChangeListener onPageChangeListener;

	private enum State {
		IDLE, GOING_LEFT, GOING_RIGHT
	}

    public HSGallery(Context context) {
        this(context, null);
    }

    public HSGallery(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("ClickableViewAccessibility") 
    public HSGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HSGallery);
        GALLEY_SCALE_RATE = a.getFloat(R.styleable.HSGallery_scaleP, GALLEY_SCALE_RATE);
        int galleryPadding = a.getDimensionPixelSize(R.styleable.HSGallery_gallery_padding, 0);
        if (galleryPadding > 0) {
            galleryPaddingLeft = galleryPaddingRight = galleryPaddingTop = galleryPaddingBottom = galleryPadding;
        } else {
            galleryPaddingLeft = a.getDimensionPixelSize(R.styleable.HSGallery_gallery_padding_left, galleryPaddingLeft);
            galleryPaddingRight = a.getDimensionPixelSize(R.styleable.HSGallery_gallery_padding_right, galleryPaddingRight);
            galleryPaddingTop = a.getDimensionPixelSize(R.styleable.HSGallery_gallery_padding_top, galleryPaddingTop);
            galleryPaddingBottom = a.getDimensionPixelSize(R.styleable.HSGallery_gallery_padding_bottom, galleryPaddingBottom);
        }
        galleryCenterMargin = a.getDimensionPixelSize(R.styleable.HSGallery_gallery_pics_space, galleryCenterMargin);
        a.recycle();
        
        LayoutInflater.from(context).inflate(R.layout.view_hsgallery_layout, this, true);
        viewPager = (WrapContentHeightViewPager) findViewById(R.id.view_pager);
        ((MarginLayoutParams)viewPager.getLayoutParams()).setMargins(galleryPaddingLeft, galleryPaddingTop, galleryPaddingRight, galleryPaddingBottom);

        viewPager.setOffscreenPageLimit(OFFSCREEN_PAGE_LIMIT);
        setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return viewPager.dispatchTouchEvent(event);
            }
        });
        
        viewPager.addOnPageChangeListener(new PageChangeListener());
        viewPager.setPageMargin(galleryCenterMargin);

        
        
    }
    
    public void setViewPagerPadding(int paddingLeft,int paddingTop,int paddingRight,int paddingBottom){
    	 ((MarginLayoutParams)viewPager.getLayoutParams()).setMargins(paddingLeft, paddingTop, paddingRight, paddingBottom);
    }
//    public void setPadding(int paddingLeft,int paddingTop,int paddingRight,int paddingBottom){
//    	if(viewPager != null){
//    		((MarginLayoutParams)viewPager.getLayoutParams()).setMargins(paddingLeft, paddingTop, paddingRight, paddingBottom);
//    	}else{
//    		super.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
//    	}
//    }
    
    public void setOnPageChangeListener(HSGalleryChangeListener onPageChangeListener){
    	this.onPageChangeListener = onPageChangeListener;
    }
    
    /**
     * 跳转到第几项
     * @param item
     */
    public void setCurrentItem(int item){
    	viewPager.setCurrentItem(item,true);
    }
    
    /**
     * 获取当前项索引
     * @return
     */
    public int getCurrentItem(){
    	
    	return viewPager.getCurrentItem();
    }
    public WrapContentHeightViewPager getViewPager(){
    	return this.viewPager;
    }
    
    public class PageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageScrolled(int position,float positionOffset, int positionOffsetPixels) {
			// TODO Auto-generated method stub
			
			if (mState == State.IDLE && positionOffset > 0) {
				oldPage = viewPager.getCurrentItem();
				mState = position == oldPage ? State.GOING_RIGHT : State.GOING_LEFT;
			}
			boolean goingRight = position == oldPage;
			if (mState == State.GOING_RIGHT && !goingRight)
				mState = State.GOING_LEFT;
			else if (mState == State.GOING_LEFT && goingRight)
				mState = State.GOING_RIGHT;
			
			float effectOffset = isSmall(positionOffset) ? 0 : positionOffset;
			
			if(hsGalleryPagerAdapter!=null){
				mLeft=hsGalleryPagerAdapter.getLiveView(position);
				mRight=hsGalleryPagerAdapter.getLiveView(position+1);
			}
		
			updateAnimation(mLeft, mRight, effectOffset);
			if (effectOffset == 0) {
				disableHardwareLayer();
				mState = State.IDLE;
			}
		
		}

		@Override
		public void onPageSelected(int position) {
			disableHardwareLayer();
			mState = State.IDLE;
			onPageChangeListener.onPageChange(position);
		}
        
    }
    private boolean isSmall(float positionOffset) {
    	
		return Math.abs(positionOffset) < 0.003;
	}
    
    @SuppressWarnings("unchecked")
	public void setAdapter(@SuppressWarnings("rawtypes") HSGalleryPagerAdapter adapter) {
    	hsGalleryPagerAdapter = adapter; 
        viewPager.setAdapter(adapter);
    }
    
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void manageLayer(View v, boolean enableHardware) {
		if (!API_11)
			return;
		int layerType = enableHardware ? View.LAYER_TYPE_HARDWARE
				: View.LAYER_TYPE_NONE;
		if (layerType != v.getLayerType())
			v.setLayerType(layerType, null);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void disableHardwareLayer() {
		if (!API_11)
			return;
		View v;
		for (int i = 0; i < getChildCount(); i++) {
			v = getChildAt(i);
			if (v.getLayerType() != View.LAYER_TYPE_NONE)
				v.setLayerType(View.LAYER_TYPE_NONE, null);
		}
	}
	
	
	/**
     * 更新pager变动动画
     * @param left 左视图
     * @param right 右视图
     * @param positionOffset  变动因子，当前页面偏移的百分比
     */
    private void updateAnimation(View left, View right, float positionOffset ) {
    	
    	if (left != null)
			ViewHelper.setAlpha(left, 1.0f);
		if (right != null)
			ViewHelper.setAlpha(right, 1.0f);
		if (mState != State.IDLE) {
			if (left != null) {
				manageLayer(left, true);
				mScale =  GALLEY_SCALE_RATE + (1 - GALLEY_SCALE_RATE) * (1 - positionOffset) ;
				ViewHelper.setPivotX(left, left.getMeasuredWidth() * 0.5f);
				ViewHelper.setPivotY(left, left.getMeasuredHeight() * 0.5f);
				ViewHelper.setScaleX(left, mScale);
				ViewHelper.setScaleY(left, mScale);
				ViewHelper.setAlpha(left, mScale*mScale*mScale*mScale);
			}
			if (right != null) {
				manageLayer(right, true);
				mScale = GALLEY_SCALE_RATE + (1 - GALLEY_SCALE_RATE) * positionOffset  ;
				ViewHelper.setPivotX(right, right.getMeasuredWidth() * 0.5f);
				ViewHelper.setPivotY(right, right.getMeasuredHeight() * 0.5f);
				ViewHelper.setScaleX(right, mScale);
				ViewHelper.setScaleY(right, mScale);
				ViewHelper.setAlpha(right, mScale*mScale*mScale*mScale);
			}
		}
    }
   
    public  interface HSGalleryChangeListener {
    	public void onPageChange(int position);
    }
  
}
